import Auth from '@/components/auth';
import PageHeader from '@/components/page-header';
import { AUTH_BTN_CODE } from '@/constants';
import demoService, { IRoleItem } from '@/services/demo';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import { BfFormTable } from '@bud-fe/react-pc-ui';
import { transferMapToOptions } from '@bud-fe/utils';
import { Button, Modal, message } from 'antd';
import { useMemo } from 'react';
import styles from './index.module.less';

const ENUM_ROLE_STATUS = {
  ENABLED: 1,
  DISENABLED: 0,
};

const MAP_ROLE_STATUS = {
  [ENUM_ROLE_STATUS.ENABLED]: '启用',
  [ENUM_ROLE_STATUS.DISENABLED]: '停用',
};

export default () => {
  const actionsColumn = BfFormTable.useActionsColumn<IRoleItem>({
    AuthWrapperComp: Auth,
    items: (record) => {
      return [
        { action: 'view', label: '查看', authKey: AUTH_BTN_CODE.roleMgt.view },
        { action: 'edit', label: '编辑', authKey: AUTH_BTN_CODE.roleMgt.edit },
        { action: 'viewMember', label: '查看成员', authKey: AUTH_BTN_CODE.roleMgt.viewMember },
        record.status
          ? { action: 'disable', label: '停用', authKey: AUTH_BTN_CODE.roleMgt.enableDisable }
          : { action: 'enable', label: '启用', authKey: AUTH_BTN_CODE.roleMgt.enableDisable },
      ];
    },
    // TODO:
    onActionBtnClick(item, record) {
      switch (item.action) {
        case 'view':
          break;
        case 'edit':
          break;
        case 'enable':
          Modal.confirm({
            title: '启用角色',
            icon: <ExclamationCircleOutlined />,
            content: `确认启用 ${record.roleName} ？`,
            onOk: () => {
              // request api...
              message.success('操作成功');
              refresh();
            },
          });
          break;
        case 'disable':
          Modal.confirm({
            title: '停用角色',
            icon: <ExclamationCircleOutlined />,
            content: `确认停用 ${record.roleName} ？`,
            onOk: () => {
              // request api...
              message.success('操作成功');
              refresh();
            },
          });
          break;
        default:
          break;
      }
    },
  });
  const { tableProps, form, search, refresh, selectedRowKeys, setSelectedRowKeys } = BfFormTable.useFormTable({
    service: (params) => {
      return demoService.getRoleList(params);
    },
    // 可选：自定义请求接口时的分页参数字段
    // pagingParamsFormatter: (pagingParams) => {
    //   const { current, pageSize } = pagingParams;
    //   return { pageNo: current, pageSize };
    // },
    // 是否开启多选模式
    multiple: true,
    /**
     * 透传 ahooks 的 useAntdTable 的 cacheKey
     * {@see https://ahooks.js.org/zh-CN/hooks/use-antd-table#%E7%BC%93%E5%AD%98}
     */
    cacheKey: '{{ kebabCase name }}',
    searchFormItems: [
      { type: 'input', name: 'roleName', label: '角色名称' },
      {
        type: 'select',
        name: 'roleStatus',
        label: '状态',
        // valueEnum: { on: '启用', off: '停用' },
        fieldProps: {
          allowClear: true,
          options: transferMapToOptions(MAP_ROLE_STATUS),
        },
      },
    ],
    tableColumns: [
      { title: '角色ID', dataIndex: 'roleCode' },
      { title: '角色名称', dataIndex: 'roleName', ellipsisLimit: 20 },
      { title: '角色描述', dataIndex: 'roleDescribe', tooltip: '这里显示气泡框' },
      { title: '创建人', dataIndex: 'ownerId' },
      { title: '最近一次更新时间', dataIndex: 'updateTime' },
      { title: '状态', dataIndex: 'roleStatus', render: (text) => MAP_ROLE_STATUS[text] },
      actionsColumn,
    ],
  });

  const actionBar = useMemo(() => {
    // TODO:
    const handleOnEnableDisable = (enableOrDisable: boolean) => {
      // request api...
      setSelectedRowKeys([]);
      refresh();
    };
    return [
      <Button type="link" disabled={!selectedRowKeys.length} onClick={() => handleOnEnableDisable(true)}>
        批量启用
      </Button>,
      <Button type="link" disabled={!selectedRowKeys.length} onClick={() => handleOnEnableDisable(false)}>
        批量停用
      </Button>,
      <Auth authKey={AUTH_BTN_CODE.roleMgt.add}>
        <Button type="primary" ghost>
          新增角色
        </Button>
      </Auth>,
      <span className={styles['text']}>文字</span>,
    ];
  }, [refresh, selectedRowKeys.length, setSelectedRowKeys]);

  const renderTabBar = () => {
    return <div>这里渲染FormTable组件上方部分</div>;
  };

  return (
    <>
      <PageHeader title="{{ kebabCase name }}" />
      <BfFormTable
        className={styles['page-{{ kebabCase name }}']}
        rowKey="roleCode"
        aboveActionBar={renderTabBar()}
        actionBarTitle="角色管理列表"
        actionBar={actionBar}
        search={search}
        form={form}
        {...tableProps}
      />
    </>
  );
};
